import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import _ from "lodash";
import {
  Button,
  Form,
  Input,
  TreeSelect,
  Radio,
  Select,
  InputNumber,
} from "antd";
import { renderTreeNodes } from "@pkgs/Layout/utils";
import useFormatMessage from "@pkgs/hooks/useFormatMessage";
import { prefixCls } from "../config";
import { getNodeTree, findNodePathById } from "../utils";
import request from "@pkgs/request";
import api from "@common/api";
import "./style.less";
import type { TreeNode } from "@pkgs/interface";
import type { DiscoveryTableListType } from "../interface";

const FormItem = Form.Item;
const { Option } = Select;

const defaultFormData = {
  nid: "",
  name: "",
  type: "ucs",
  service_id: "",
  collect_path: "",
  port: null,
  metrics_path: "",
  idc: "",
  role: "",
  cluster: "",
  shard: "",
  keyword: "",
};

const getInitialValues = (initialValues: DiscoveryTableListType) => {
  return _.assignIn({}, defaultFormData, _.cloneDeep(initialValues));
};

const getCollectServiceData = async (nodeId: number) => {
  try {
    const data = await request(
      `${api.collect}/list?nid=${nodeId}&type=service&watch_range=review`
    );
    return data;
  } catch {}
};

const STREEForm = (props: any) => {
  const intlFmtMsg = useFormatMessage();
  const initialValues = getInitialValues(props.initialValues);
  const { getFieldProps, getFieldDecorator } = props.form;
  const { treeData } = props;
  const [collectTree, setCollectTree] = useState<TreeNode[]>();
  const [selectNodeId, setSelectNodeId] = useState<number>();
  const [collectServiceData, setCollectServiceData] = useState([]);

  useEffect(() => {
    const data: TreeNode[] = getNodeTree(treeData, initialValues.nid);
    setCollectTree(data);
  }, [treeData, initialValues.nid]);

  useEffect(() => {
    if (!initialValues.nid) return;
    if (selectNodeId !== undefined) {
      getCollectServiceData(selectNodeId).then((res) => {
        res && setCollectServiceData(res);
      });
    } else {
      getCollectServiceData(initialValues.nid).then((res) => {
        res && setCollectServiceData(res);
      });
    }
  }, [treeData, selectNodeId, initialValues.nid]);

  const [submitLoading, setSubmitLoading] = useState(false);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    props.form.validateFields((errors: any, values: any) => {
      if (errors) {
        console.error(errors);
        return;
      }
      setSubmitLoading(true);
      if (values.collect_path && typeof values.collect_path === "number") {
        const { collect_path } = values;
        const newPath = findNodePathById(treeData, collect_path);
        values.collect_path = newPath;
      }
      if (values.service_id == "") {
        values.service_id = 0;
      }
      props.onSubmit(values).catch(() => {
        setSubmitLoading(false);
      });
    });
    setSubmitLoading(false);
  };

  return (
    <div className={`${prefixCls}-zeus-discovery-form`}>
      <Form layout="horizontal" onSubmit={handleSubmit}>
        <FormItem
          label={<strong>{intlFmtMsg({ id: "collect.common.node" })}</strong>}
        >
          {getFieldDecorator("nid", {
            initialValue: initialValues.nid,
            rules: [{ required: true, message: "请选择节点！" }],
          })(
            <TreeSelect
              style={{ width: 500 }}
              showSearch
              allowClear
              treeDefaultExpandAll
              treeNodeFilterProp="path"
              treeNodeLabelProp="path"
              onChange={(value: number) => {
                const data: TreeNode[] = getNodeTree(treeData, value);
                setSelectNodeId(value);
                setCollectTree(data);
              }}
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
            >
              {renderTreeNodes(treeData, "treeSelect")}
            </TreeSelect>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>发现通道:</strong>
              <span>prometheus的任务执行通道，一般选ucs</span>
            </>
          }
        >
          {getFieldDecorator("type", {
            initialValue: initialValues.type,
          })(
            <Radio.Group>
              <Radio value="ucs">UCS</Radio>
              <Radio value="exporter">exporter</Radio>
              <Radio value="instance">Instance</Radio>
            </Radio.Group>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>服务名称:</strong>
              <span>app名称，必须英文，供grafana配图筛选</span>
            </>
          }
        >
          <Input
            {...getFieldProps("name", {
              initialValue: initialValues.name,
              rules: [{ required: true, message: "必填项！" }],
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>归属服务:</strong>
              <span>
                选填，配置挂载至特定服务，统一监控元数据，服务配置见
                采集配置→服务
              </span>
            </>
          }
        >
          {getFieldDecorator("service_id", {
            initialValue: initialValues.service_id,
          })(
            <Select style={{ width: 500 }}>
              {collectServiceData.map((item: any) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>采集节点:</strong>
              <span>
                基于的服务树节点发现机器列表，采集指标为：节点下机器名:监控端口/监控路径
              </span>
            </>
          }
        >
          {getFieldDecorator("collect_path", {
            initialValue: initialValues.collect_path,
            rules: [{ required: true, message: "请选择节点！" }],
          })(
            <TreeSelect
              style={{ width: 500 }}
              showSearch
              allowClear
              treeDefaultExpandAll
              treeNodeFilterProp="path"
              treeNodeLabelProp="path"
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
            >
              {renderTreeNodes(collectTree as TreeNode[], "treeSelect")}
            </TreeSelect>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>监控端口:</strong>
              <span>采集监控指标的端口号</span>
            </>
          }
        >
          <InputNumber
            {...getFieldProps("port", {
              initialValue: initialValues.port,
              rules: [{ required: true, message: "必填项！" }],
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>监控路径:</strong>
              <span>采集指标的路径，一般为/metrics</span>
            </>
          }
        >
          <Input
            {...getFieldProps("metrics_path", {
              initialValue: initialValues.metrics_path,
              rules: [{ required: true, message: "必填项！" }],
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>机房筛选:</strong>
              <span>
                选填，不填写则基于节点自动匹配机器所在机房，若填写只采集筛选机房的机器，机房逗号分割例如：
                zzzc,shbt
              </span>
            </>
          }
        >
          <Input
            {...getFieldProps("idc", {
              initialValue: initialValues.idc,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>主从筛选:</strong>
              <span>
                选填,见stree.io→机器→table内主从名称，若配置可以此筛选
              </span>
            </>
          }
        >
          <Input
            {...getFieldProps("role", {
              initialValue: initialValues.role,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>集群筛选:</strong>
              <span>
                选填，基于节点+集群筛选机器列表，集群见stree.io-&gt;机器-&gt;table内集群名称
              </span>
            </>
          }
        >
          <Input
            {...getFieldProps("cluster", {
              initialValue: initialValues.cluster,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>分片筛选:</strong>
              <span>
                选填,见stree.io→机器→table内分片名称，若配置可以此筛选，逗号分割
              </span>
            </>
          }
        >
          <Input
            {...getFieldProps("shard", {
              initialValue: initialValues.shard,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>关键字筛选:</strong>
              <span>选填，若配置机器hostname需要匹配此关键字才会采集</span>
            </>
          }
        >
          <Input
            {...getFieldProps("keyword", {
              initialValue: initialValues.keyword,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem wrapperCol={{ offset: 6 }} style={{ marginTop: 24 }}>
          <Button type="primary" htmlType="submit" loading={submitLoading}>
            {intlFmtMsg({ id: "form.submit" })}
          </Button>
          <Button style={{ marginLeft: 8 }}>
            <Link
              to={{
                pathname: "/prometheus/discovery",
                search: window.location.search,
              }}
            >
              {intlFmtMsg({ id: "form.goback" })}
            </Link>
          </Button>
        </FormItem>
      </Form>
    </div>
  );
};

export default Form.create()(STREEForm);
